package in.iqing.view.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.lidroid.xutils.db.sqlite.Selector;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import in.iqing.app.R;
import in.iqing.base.BaseActivity;
import in.iqing.control.adapter.DirectoryAdapter;
import in.iqing.control.adapter.DownloadBookAdapter;
import in.iqing.control.helper.IntentHelper;
import in.iqing.control.helper.LogHelper;
import in.iqing.model.bean.Book;
import in.iqing.model.bean.Chapter;
import in.iqing.model.bean.DownloadedBook;
import in.iqing.model.bean.History;
import in.iqing.model.bean.Volume;
import in.iqing.model.db.DBHelper;
import in.iqing.module.download.BookTask;
import in.iqing.module.download.DownloadManager;
import in.iqing.view.widget.SimpleDividerItemDecoration;

/**
 * Created by ZuoShu on 2015/7/17.
 */
public class DownloadListActivity extends BaseActivity {
    @Bind(R.id.download_list_recycler)
    RecyclerView bookRecycler;

    DownloadBookAdapter downloadBookAdapter;

    @Bind(R.id.cache_layout)
    View cacheLayout;

    @Bind(R.id.cache_menu)
    View cacheMenu;

    @Bind(R.id.select_all_checkbox)
    CheckBox selectAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_list);
    }

    @Override
    protected void onInitialize(Bundle savedInstanceState) {
        super.onInitialize(savedInstanceState);
        setRecyclerView();
        loadDownloadBookData();
    }

    private void setRecyclerView() {
        downloadBookAdapter = new DownloadBookAdapter(this);
        bookRecycler.setAdapter(downloadBookAdapter);
        bookRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        bookRecycler.addItemDecoration(new SimpleDividerItemDecoration(getContext()));
        downloadBookAdapter.setListener(new ExtItemCallback());
    }

    private void loadDownloadBookData() {
        List<DownloadedBook> downloadedBooks = getDownloadedBookData();
        if (downloadedBooks == null || downloadedBooks.size() == 0) {
            showEmpty();
            cacheMenu.setVisibility(View.GONE);
        } else {
            showContent();
            downloadBookAdapter.setBooks(downloadedBooks);
        }
    }

    private List<DownloadedBook> getDownloadedBookData() {
        List<Book> books = DBHelper.getInstance().find(Selector.from(Book.class).where("cached_chapter_count", ">", 0));
        if (books == null || books.size() == 0) {
            return null;
        } else {
            List<DownloadedBook> downloadedBooks = new ArrayList<>();
            for (Book book : books) {
                BookTask bookTask = DBHelper.getInstance().getBookTask(book);
                DownloadedBook downloadedBook = new DownloadedBook();
                downloadedBook.setBookId(book.getId());
                downloadedBook.setTitle(book.getTitle());
                downloadedBook.setDownloadPercent(getDownloadPercentString(book));
                downloadedBook.setReadPercent(getReadPercentString(book));
                downloadedBook.setAuthor(getString(R.string.activity_download_list_author, book.getAuthor()));
                downloadedBook.setPress(getString(R.string.activity_download_list_press, book.getPress()));
                if (bookTask != null) {
                    downloadedBook.setCover(bookTask.getCover());
                }
                downloadedBooks.add(downloadedBook);
            }
            return downloadedBooks;
        }
    }

    private String getDownloadPercentString(Book book) {
        if (book.getChapterCount() == 0) {
            return getString(R.string.activity_download_list_download_progress, String.valueOf("0%"));
        } else {
            return getString(R.string.activity_download_list_download_progress,
                    String.valueOf(NumberFormat.getPercentInstance().format(
                            (float) (book.getCachedChapterCount()) / (float) (book.getChapterCount())
                    ))
            );
        }
    }

    private String getReadPercentString(Book book) {
        History history = DBHelper.getInstance().getBookmark(book.getId());
        if (history == null) {
            return getString(R.string.activity_download_list_read_progress, String.valueOf("0%"));
        }

        int readChapterIndex = 0;
        // go over all chapters to find last read chapter index
        List<Volume> volumes = DBHelper.getInstance().getBookVolumes(book);
        if (volumes == null || volumes.size() == 0) {
            return getString(R.string.activity_download_list_read_progress, String.valueOf("0%"));
        }
        for (Volume volume : volumes) {
            List<Chapter> chapters = DBHelper.getInstance().getVolumeChapters(volume);
            if (chapters == null || chapters.size() == 0) {
                continue;
            }
            for (Chapter chapter : chapters) {
                if (chapter.getId() == history.getChapterId()) {
                    return getString(R.string.activity_download_list_read_progress,
                            String.valueOf(NumberFormat.getPercentInstance().format(
                                    (float) (readChapterIndex) / (float) (book.getChapterCount())
                            ))
                    );
                } else {
                    readChapterIndex++;
                }
            }
        }
        return getString(R.string.activity_download_list_read_progress, String.valueOf("0%"));
    }

    @OnClick(R.id.back)
    public void onBackClick(View v) {
        finish();
    }

    @OnClick(R.id.cache_menu)
    public void onCacheMenuClick(View v) {
        downloadBookAdapter.setIsOperating(cacheLayout.getVisibility() != View.VISIBLE);
        downloadBookAdapter.notifyDataSetChanged();
        cacheLayout.setVisibility(cacheLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
    }

    @OnClick(R.id.delete_cache)
    public void onDeleteCacheClick(View v) {
        Set<DownloadedBook> deleteBooks = downloadBookAdapter.getSelectedBook();
        if (deleteBooks == null || deleteBooks.size() == 0) {
            LogHelper.warn(TAG, "no select downloaded book, skip delete");
            return;
        }

        for (DownloadedBook downloadedBook : deleteBooks) {
            Book book = DBHelper.getInstance().getBook(downloadedBook);
            DownloadManager.getInstance().delete(book);
        }

        downloadBookAdapter.deleteSelected();
        downloadBookAdapter.notifyDataSetChanged();
        cacheLayout.setVisibility(View.GONE);
    }

    @OnCheckedChanged(R.id.select_all_checkbox)
    public void onSelectAllChecked(CompoundButton compoundButton, boolean checked) {
        if (checked) {
            downloadBookAdapter.selectAll();
            selectAll.setText(R.string.activity_download_list_deselect_all);
        } else {
            downloadBookAdapter.deselectAll();
            selectAll.setText(R.string.activity_download_list_select_all);
        }
        downloadBookAdapter.notifyDataSetChanged();
    }

    private class ExtItemCallback implements DownloadBookAdapter.Callback {

        @Override
        public void onItemClick(DownloadedBook downloadBook) {
            Book book = DBHelper.getInstance().getBook(downloadBook);
            Bundle data = new Bundle();
            data.putSerializable("book", book);
            IntentHelper.startActivity(DownloadListActivity.this, CachedDirectoryActivity.class, data);
        }

        @Override
        public void onCheckedChange(DownloadedBook book, boolean checked) {
            if (downloadBookAdapter.getSelectedBook().size() == downloadBookAdapter.getBooks().size()) {
                selectAll.setChecked(true);
                selectAll.setText(R.string.activity_download_list_deselect_all);
            } else {
                selectAll.setChecked(false);
                selectAll.setText(R.string.activity_download_list_select_all);
            }
        }
    }


}
